package com.ahoi.controller;

import com.ahoi.common.base.BaseController;
import com.ahoi.common.base.ResponseJson;
import com.ahoi.common.constant.CommonEnum;
import com.ahoi.common.constant.Constants;
import com.ahoi.common.constant.MyConfig;
import com.ahoi.common.utils.HttpUtils;
import com.ahoi.common.utils.StringUtils;
import com.ahoi.common.utils.ThreadUtils;
import com.ahoi.model.BookInfo;
import com.ahoi.service.BookInfoService;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;


@RestController
@RequestMapping(value = "BookInfo")
public class BookInfoController extends BaseController {
    private static Logger logger = LoggerFactory.getLogger(BookInfoController.class);

    @Autowired
    private BookInfoService bookInfoService;
    @Autowired
    private MyConfig myConfig;

    @RequestMapping(value = "/listPage", name = "获取小说列表")
    public void listPage(HttpServletRequest request, HttpServletResponse response, BookInfo query) {
        try {
            PageInfo<BookInfo> page = bookInfoService.listPage(query);
            ResponseJson.writeSuccess(response, page);
        } catch (Exception e) {
            e.printStackTrace();
            ResponseJson.writeError(response);
        }
    }

    @RequestMapping(value = "/status", name = "查询扫描是否结束")
    public void status(HttpServletRequest request, HttpServletResponse response) {
        try {
            if (Constants.SERVICE_STARTING) {
                ResponseJson.writeError(response, "扫描服务正在运行");
            } else {
                ResponseJson.writeSuccess(response, "扫描完毕");
            }
        } catch (Exception e) {
            e.printStackTrace();
            ResponseJson.writeError(response);
        }
    }

    @RequestMapping(value = "/scan", name = "对外接口，开始扫描")
    public void scan(HttpServletRequest request, HttpServletResponse response) {
        try {
            if (Constants.SERVICE_STARTING) {
                ResponseJson.writeError(response, "扫描服务已开启，请等待本次扫描结束后再试");
                return;
            }
            Constants.SERVICE_STARTING = true;

            // 重置所有记录的状态为未更新
            bookInfoService.updatedToInit();

            // 重置线程请求数为0
            ThreadUtils.iniThreadAliveCount(0);

            // 循环发起线程请求
            String bookListUrl = myConfig.getBookListUrl();
            Integer totalPage = bookInfoService.getTotalPage(bookListUrl);
            if (totalPage > 0) {
                int start = 0, end = 100;
                while (true) {
                    if (end > totalPage) {
                        end = totalPage;
                    }

                    // 线程请求数自增
                    ThreadUtils.incThreadAliveCount();
                    HttpUtils.get("http://localhost:1515/BookInfo/insert.do?start=" + start + "&end=" + end);
                    if (end == totalPage) {
                        break;
                    }
                    start = end + 1;
                    end += 100;
                }
            }
            logger.info("all request is send...");
            ResponseJson.writeSuccess(response);
        } catch (Exception e) {
            Constants.SERVICE_STARTING = false;
            e.printStackTrace();
            ResponseJson.writeError(response);
        }
    }

    @RequestMapping(value = "/insert", name = "开始请求网页并解析内容保存小说基本信息")
    public void insert(HttpServletRequest request, HttpServletResponse response) {
        try {
            String bookListUrl = myConfig.getBookListUrl();
            Integer start = Integer.parseInt(request.getParameter("start"));
            Integer end = Integer.parseInt(request.getParameter("end"));

            // 单独线程开始请求
            ThreadUtils.startNewThread("scan-and-insert-[" + start + "-" + end + "]", new Runnable() {
                @Override
                public void run() {
                    bookInfoService.scanAndInsertBooks(start, end, bookListUrl);
                }
            });
            ResponseJson.writeSuccess(response);
        } catch (Exception e) {
            e.printStackTrace();
            ResponseJson.writeError(response);
        }
    }

    @RequestMapping(value = "/update", name = "对外暴露接口，开始更新小说详细信息")
    public void update(HttpServletRequest request, HttpServletResponse response) {
        try {
            // 重置所有记录的状态为未更新
            bookInfoService.updatedToInit();

            // 查询未更新的数据
            BookInfo query = new BookInfo();
            query.setPageNum(1);
            query.setPageSize(100000);
            query.setSelectColumns("id");
            query.setUpdated(CommonEnum.NO.getCode());

            List<BookInfo> bookInfos = bookInfoService.listPage(query).getList();
            while (bookInfos != null && bookInfos.size() > 0) {

                List<BookInfo> finalBookInfos = bookInfos;
                ThreadUtils.startNewThread("load-for-detail", new Runnable() {
                    @Override
                    public void run() {
                        // 每100条记录发送一次新请求处理
                        String ids = "";
                        for (int i = 0; i < finalBookInfos.size(); i++) {
                            ids += finalBookInfos.get(i).getId();
                            if (i % 100 == 0 || i == finalBookInfos.size() - 1) {
                                HttpUtils.get("http://localhost:1515/BookInfo/loadForDetail.do?ids=" + ids);
                                ids = "";
                            }
                            if (StringUtils.isNotEmpty(ids)) {
                                ids += ",";
                            }
                        }
                    }
                });

                // 更新这一批记录为已更新
                bookInfoService.updatedToUpdated(bookInfos);
                bookInfos = bookInfoService.listPage(query).getList();
            }

            ResponseJson.writeSuccess(response);
        } catch (Exception e) {
            e.printStackTrace();
            ResponseJson.writeError(response);
        }
    }

    @RequestMapping(value = "/loadForDetail", name = "获取小说详细信息")
    public void loadForDetail(HttpServletRequest request, HttpServletResponse response) {
        try {
            String bookDetailUrl = myConfig.getBookDetailUrl();
            String ids = request.getParameter("ids");
            if (StringUtils.isNotEmpty(ids)) {
                BookInfo query = new BookInfo();
                query.setIds(ids);
                List<BookInfo> bookInfos = bookInfoService.listData(query);

                ThreadUtils.startNewThread("update-detail-info", new Runnable() {
                    @Override
                    public void run() {
                        bookInfoService.loadForDetail(bookInfos, bookDetailUrl);
                    }
                });
            }
            ResponseJson.writeSuccess(response);
        } catch (Exception e) {
            e.printStackTrace();
            ResponseJson.writeError(response);
        }
    }

    @RequestMapping(value = "/errorUrl", name = "从错误请求列表里面重新请求")
    public void errorUrl(HttpServletRequest request, HttpServletResponse response) {
        try {
            int size = bookInfoService.scanFromErrorUrl();
            ResponseJson.writeSuccess(response, size);
        } catch (Exception e) {
            e.printStackTrace();
            ResponseJson.writeError(response);
        }
    }


}
